package org.example.ams.service.impl.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.ams.dao.system.ISysScheduledDao;
import org.example.ams.entity.system.SysScheduled;
import org.example.ams.service.system.ISysScheduledService;
import org.example.ams.task.config.SchedulingTask;
import org.example.ams.task.config.TaskRegister;
import org.example.ams.util.SystemUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysScheduledServiceImpl implements ISysScheduledService {

    @Autowired
    private ISysScheduledDao sysScheduledDao;
    @Autowired
    private TaskRegister taskRegister;
    @Autowired
    private SystemUtils loginContextUtils;

    @Override
    public SysScheduled queryById(String scheduledId) {
        return sysScheduledDao.selectById(scheduledId);
    }

    /**
     * 分页查询
     * @param currentPage
     * @param pageSize
     * @param params
     * @return
     */
    @Override
    public Map<String,Object> queryByPage(Integer currentPage, Integer pageSize, Map<String, String[]> params){
        QueryWrapper<SysScheduled> queryWrapper = new QueryWrapper<SysScheduled>();
        if (params.get("scheduledName") != null && !"".equals(params.get("scheduledName"))) {
            queryWrapper = queryWrapper.like("scheduled_name",params.get("scheduledName")[0]);
        }
        queryWrapper = queryWrapper.orderByDesc("create_time");
        Page<SysScheduled> page = new Page<SysScheduled>(currentPage,pageSize);
        Page<SysScheduled> ipage = null;
        ipage = sysScheduledDao.selectPage(page, queryWrapper);
        // 数据转化
        Map<Integer, String> userIdToNameMapper = loginContextUtils.getUserIdToNameMapper();
        List<SysScheduled> records = ipage.getRecords();
        for (SysScheduled record : records) {
            record.setCreateUserName(userIdToNameMapper.get(record.getCreateUserId()));
            record.setUpdateUserName(userIdToNameMapper.get(record.getUpdateUserId()));
        }
        Map<String,Object> res = new HashMap<>();
        res.put("total",ipage.getTotal());
        res.put("data",records);
        return res;
    }


    @Override
    public void save(SysScheduled sysScheduled) {
        sysScheduledDao.insert(sysScheduled);
    }

    @Override
    public List<SysScheduled> queryBootstrapedTask() {
        return sysScheduledDao.selectList(new QueryWrapper<SysScheduled>().eq("status",1));
    }


    @Override
    public boolean updateStatus(String scheduledId,Integer status) {
        int row = sysScheduledDao.update(null,new UpdateWrapper<SysScheduled>()
                .set("status",status).set("update_time",new Date()).eq("id",scheduledId));
        if (row == 0) {
            return false;
        }
        return true;
    }

    @Override
    public List<SysScheduled> list() {
        return sysScheduledDao.selectList(null);
    }

    @Override
    public int remove(String id) {
        return sysScheduledDao.deleteById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addTask(SysScheduled sysScheduled) {
        SysScheduled scheduled = sysScheduledDao.selectById(sysScheduled.getId());
        if (scheduled != null) {
            // 如果已经存在，先删除掉原来的
            int row = sysScheduledDao.deleteById(scheduled.getId());
            if (row == 1) {
                taskRegister.removeTask(scheduled.getId());
            } else {
                return;
            }
        }
        // 设置默认值 添加后启动
        sysScheduled.setStatus(true);
        sysScheduled.setCreateTime(new Date());
        sysScheduled.setUpdateTime(new Date());
        sysScheduled.setCreateUserId(loginContextUtils.loginUser().getUserId());
        sysScheduled.setUpdateUserId(loginContextUtils.loginUser().getUserId());
        int row = sysScheduledDao.insert(sysScheduled);
        if (row == 1) {
            SchedulingTask task = new SchedulingTask(sysScheduled);
            taskRegister.registerTask(task,sysScheduled.getCron());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateTask(SysScheduled sysScheduled) {
        // 1. 更新数据库
        int row = sysScheduledDao.updateById(sysScheduled);
        if (row == 1) {
            // 2. 如果任务原来已启动，则停止任务
            taskRegister.removeTask(sysScheduled.getId());
            // 3. 判断更新后的任务的状态
            if (sysScheduled.isStatus()) {
                // 启动任务
                SchedulingTask task = new SchedulingTask(sysScheduled);
                taskRegister.registerTask(task,sysScheduled.getCron());
            }
            return true;
        }
        return false;
    }
}
